package com.hbnu.sunjianwei.questionbank.util;

import com.hbnu.sunjianwei.questionbank.entity.ExamPaper;
import com.hbnu.sunjianwei.questionbank.entity.Question;
import org.apache.poi.xwpf.usermodel.*;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTblWidth;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STTblWidth;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * Word文档导出工具类
 */
public class WordExportUtil {

    /**
     * 导出试卷为Word文档
     */
    public static boolean exportExamToWord(ExamPaper examPaper, String filePath) {
        try (XWPFDocument document = new XWPFDocument()) {
            // 创建标题
            createTitle(document, examPaper.getTitle());

            // 创建试卷信息
            createExamInfo(document, examPaper);

            // 创建题目列表
            createQuestions(document, examPaper.getQuestions());

            // 保存文档
            return saveDocument(document, filePath);
        } catch (IOException e) {
            System.err.println("❌ 导出Word文档失败: " + e.getMessage());
            return false;
        }
    }

    /**
     * 导出答案为Word文档
     */
    public static boolean exportAnswersToWord(ExamPaper examPaper, String filePath) {
        try (XWPFDocument document = new XWPFDocument()) {
            // 创建标题
            createTitle(document, examPaper.getTitle() + " - 参考答案");

            // 创建试卷信息
            createExamInfo(document, examPaper);

            // 创建答案列表
            createAnswers(document, examPaper.getQuestions());

            // 保存文档
            return saveDocument(document, filePath);
        } catch (IOException e) {
            System.err.println("❌ 导出答案Word文档失败: " + e.getMessage());
            return false;
        }
    }

    /**
     * 创建文档标题
     */
    private static void createTitle(XWPFDocument document, String title) {
        XWPFParagraph titleParagraph = document.createParagraph();
        titleParagraph.setAlignment(ParagraphAlignment.CENTER);

        XWPFRun titleRun = titleParagraph.createRun();
        titleRun.setText(title);
        titleRun.setBold(true);
        titleRun.setFontSize(16);
        titleRun.setFontFamily("宋体");

        // 添加空行
        document.createParagraph().createRun().addBreak();
    }

    /**
     * 创建试卷信息
     */
    private static void createExamInfo(XWPFDocument document, ExamPaper examPaper) {
        XWPFParagraph infoParagraph = document.createParagraph();

        XWPFRun infoRun = infoParagraph.createRun();
        infoRun.setText("生成时间: " + formatDateTime(examPaper.getCreateTime()));
        infoRun.addBreak();
        infoRun.setText("题目数量: " + examPaper.getQuestions().size() + " 题");
        infoRun.setFontSize(12);
        infoRun.setFontFamily("宋体");

        // 添加空行
        document.createParagraph().createRun().addBreak();
    }

    /**
     * 创建题目列表
     */
    private static void createQuestions(XWPFDocument document, List<Question> questions) {
        for (int i = 0; i < questions.size(); i++) {
            Question question = questions.get(i);

            // 题目序号和内容
            XWPFParagraph questionParagraph = document.createParagraph();
            XWPFRun questionRun = questionParagraph.createRun();
            questionRun.setText((i + 1) + ". " + question.getQuestionText());
            questionRun.setBold(true);
            questionRun.setFontSize(12);
            questionRun.setFontFamily("宋体");
            questionRun.addBreak();

            // 题目信息（科目、难度）
            XWPFRun infoRun = questionParagraph.createRun();
            infoRun.setText("   [科目: " + question.getSubject() +
                    " | 难度: " + getDifficultyName(question.getDifficulty()) + "]");
            infoRun.setFontSize(10);
            infoRun.setFontFamily("宋体");
            infoRun.setColor("666666");
            infoRun.addBreak();

            // 选项
            if ("TRUE_FALSE".equals(question.getQuestionType())) {
                createTrueFalseOptions(questionParagraph);
            } else {
                createMultipleChoiceOptions(questionParagraph, question);
            }

            // 添加空行
            document.createParagraph().createRun().addBreak();
        }
    }

    /**
     * 创建判断题选项
     */
    private static void createTrueFalseOptions(XWPFParagraph paragraph) {
        XWPFRun optionRun = paragraph.createRun();
        optionRun.setText("   A. 正确");
        optionRun.setFontSize(12);
        optionRun.setFontFamily("宋体");
        optionRun.addBreak();

        optionRun = paragraph.createRun();
        optionRun.setText("   B. 错误");
        optionRun.setFontSize(12);
        optionRun.setFontFamily("宋体");
        optionRun.addBreak();
    }

    /**
     * 创建选择题选项
     */
    private static void createMultipleChoiceOptions(XWPFParagraph paragraph, Question question) {
        if (question.getOptionA() != null && !question.getOptionA().isEmpty()) {
            XWPFRun optionRun = paragraph.createRun();
            optionRun.setText("   A. " + question.getOptionA());
            optionRun.setFontSize(12);
            optionRun.setFontFamily("宋体");
            optionRun.addBreak();
        }

        if (question.getOptionB() != null && !question.getOptionB().isEmpty()) {
            XWPFRun optionRun = paragraph.createRun();
            optionRun.setText("   B. " + question.getOptionB());
            optionRun.setFontSize(12);
            optionRun.setFontFamily("宋体");
            optionRun.addBreak();
        }

        if (question.getOptionC() != null && !question.getOptionC().isEmpty()) {
            XWPFRun optionRun = paragraph.createRun();
            optionRun.setText("   C. " + question.getOptionC());
            optionRun.setFontSize(12);
            optionRun.setFontFamily("宋体");
            optionRun.addBreak();
        }

        if (question.getOptionD() != null && !question.getOptionD().isEmpty()) {
            XWPFRun optionRun = paragraph.createRun();
            optionRun.setText("   D. " + question.getOptionD());
            optionRun.setFontSize(12);
            optionRun.setFontFamily("宋体");
            optionRun.addBreak();
        }
    }

    /**
     * 创建答案列表
     */
    private static void createAnswers(XWPFDocument document, List<Question> questions) {
        // 创建表格
        XWPFTable table = document.createTable();

        // 设置表格宽度
        CTTblWidth tblWidth = table.getCTTbl().addNewTblPr().addNewTblW();
        tblWidth.setType(STTblWidth.DXA);
        tblWidth.setW(BigInteger.valueOf(9000));

        // 创建表头
        XWPFTableRow headerRow = table.getRow(0);
        headerRow.getCell(0).setText("题号");
        headerRow.addNewTableCell().setText("题目");
        headerRow.addNewTableCell().setText("正确答案");

        // 添加数据行
        for (int i = 0; i < questions.size(); i++) {
            Question question = questions.get(i);
            XWPFTableRow dataRow = table.createRow();

            dataRow.getCell(0).setText(String.valueOf(i + 1));
            dataRow.getCell(1).setText(question.getQuestionText());
            dataRow.getCell(2).setText(formatCorrectAnswer(question));
        }
    }

    /**
     * 保存文档
     */
    private static boolean saveDocument(XWPFDocument document, String filePath) {
        try {
            // 创建目录
            File directory = new File(filePath).getParentFile();
            if (!directory.exists()) {
                directory.mkdirs();
            }

            // 保存文件
            try (FileOutputStream out = new FileOutputStream(filePath)) {
                document.write(out);
            }

            System.out.println("✅ Word文档已导出: " + filePath);
            return true;
        } catch (IOException e) {
            System.err.println("❌ 保存Word文档失败: " + e.getMessage());
            return false;
        }
    }

    /**
     * 格式化时间显示
     */
    private static String formatDateTime(String dateTime) {
        try {
            LocalDateTime time = LocalDateTime.parse(dateTime);
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy年MM月dd日 HH:mm:ss");
            return time.format(formatter);
        } catch (Exception e) {
            return dateTime;
        }
    }

    /**
     * 获取难度中文名称
     */
    private static String getDifficultyName(String difficulty) {
        switch (difficulty) {
            case "EASY": return "简单";
            case "MEDIUM": return "中等";
            case "HARD": return "困难";
            default: return difficulty;
        }
    }

    /**
     * 格式化正确答案显示
     */
    private static String formatCorrectAnswer(Question question) {
        String answer = question.getCorrectAnswer();
        if ("TRUE_FALSE".equals(question.getQuestionType())) {
            return "A".equals(answer) ? "正确" : "错误";
        }
        return answer;
    }

    /**
     * 生成文件名（包含时间戳）
     */
    public static String generateFileName(String prefix) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd_HHmmss");
        String timestamp = LocalDateTime.now().format(formatter);
        return prefix + "_" + timestamp + ".docx";
    }
}